package com.rs.util;

import java.text.*;
import java.util.*;

public class DateUtil {
	
	public static String getNumberRange(String text, String separator, int startNumber){
		int maxNumber = getMaxNumber(text, separator);
		String result = getRange(maxNumber, separator, startNumber);
		return result;
	}

	public static int getMaxNumber(String text, String separator){
		String[] data = text.split(separator);
		List<String> dataList = new ArrayList<String>();
		for (int i = 0; i < data.length; i++) {
			dataList.add(data[i]);
		}
		Collections.sort(dataList);
		Collections.reverse(dataList);
		int maxNumber = Integer.parseInt(dataList.get(0));
		return maxNumber;
	}
	
	public static String getRange(int maxNumber, String separator, int startNumber){
		StringBuilder sb = new StringBuilder();
		for (int i = startNumber; i <= maxNumber ; i++) {
			if (i == maxNumber) {
				if (i < 10) {
					sb.append("0" + i);
				}else{
					sb.append(i);
				}
			}else {
				if (i < 10) {
					sb.append("0" + i + ",");
				}else{
					sb.append(i + ",");
				}
			}
		}
		return sb.toString();
	}

    public static String[] getDateRange(String[] date, int startNumber){
        int maxNumber = getMaxDate(date);
        String[] result = getDateRange(maxNumber, startNumber);
        return result;
    }

    public static int getMaxDate(String[] date){
        List<String> dataList = new ArrayList<String>();
        for (int i = 0; i < date.length; i++) {
            dataList.add(date[i]);
        }
        Collections.sort(dataList);
        Collections.reverse(dataList);
        int maxNumber = Integer.parseInt(dataList.get(0));
        return maxNumber;
    }

    public static String[] getDateRange(int maxNumber, int startNumber){
        List<String> dateList = new ArrayList<String>();
        for (int i = startNumber; i <= maxNumber ; i++) {
            if (i < 10) {
                dateList.add("0" + i);
            }else{
                dateList.add(String.valueOf(i));
            }
        }
        return dateList.toArray(new String[dateList.size()]);
    }
	
	public static List<String> getSortDate(List<String> date) {
		Set<String> set = new HashSet<String>();
		for (int i = 0; i < date.size(); i++) {
			set.add(date.get(i));
		}
		List<String> result = new ArrayList<String>(set);
		Collections.sort(result);
		return result;
	}
	
	public static List<String> getSortDate(List<String> date, int limit) {
		List<String> result = getSortDate(date);
		if (result.size() > limit) {
			result = result.subList(result.size() - limit, result.size());
		}
		return result;
	}
	
	public static List<String> getSortDate(List<String> date, String sortBy) {
		List<String> result = getSortDate(date);
		if (sortBy.equals("desc")) {
			Collections.reverse(result);
		}
		return result;
	}

    public static int getDayOfMonth(int m){
        Calendar aCalendar = Calendar.getInstance(Locale.CHINA);
        if(m>0){
            aCalendar.set(Calendar.DATE, 1);
            aCalendar.set(Calendar.MONTH,m);
        }
        int day=aCalendar.getActualMaximum(Calendar.DATE);
        return day;
    }

    /**
     * 获得当前日期的天
     * @return
     */
    public static int getDayOfMonth(){
        Calendar aCalendar = Calendar.getInstance(Locale.CHINA);
        int month = aCalendar.get(Calendar.DAY_OF_MONTH);
        return month;
    }

    /**
     * 获得本年的当前月份
     * @return
     */
    public static int getMonthOfYear(){
        Calendar aCalendar = Calendar.getInstance(Locale.CHINA);
        int month = aCalendar.get(Calendar.MONTH) + 1;

        return month;
    }

    /**
     * 当前月的前一个月
     * @return
     */
    public static int getBeforeAMonth(){
        Calendar aCalendar = Calendar.getInstance(Locale.CHINA);
        int month = aCalendar.get(Calendar.MONTH);

        return month;
    }

    /**
     * 获得本年
     * @return
     */
    public static int getYear(){
        Calendar aCalendar = Calendar.getInstance(Locale.CHINA);
        int year = aCalendar.get(Calendar.YEAR);
        return year;
    }

    /**
     * 获得去年年份
     * @return
     */
    public static int getPrevYear(){
        Calendar aCalendar = Calendar.getInstance(Locale.CHINA);
        int year = aCalendar.get(Calendar.YEAR) - 1;
        return year;
    }

    /**
     * 根据年份向前推N年的年份集合
     * @param year 年份
     * @param n 向前推N年
     * @return 年份集合字符串，逗号分隔
     */
    public static String getYearsAgoString(int year, int n){
        String years = "";
        for(int i = year; i >= year - n; n--){
            if(years.equals("")){
                years = year - n + "";
            }else{
                years += "," + (year - n);
            }
        }
        return years;
    }

    /**
     * 求一年的第一天是周几
     * date 字符串日期
     */
    public static int getDayOfWeek(String date)
    {
        int year = Integer.parseInt(date.substring(0, 4));
        int month = 0;// 月是 0-11
        int day = 1;
        String[] weekDays = DateFormatSymbols.getInstance(Locale.CHINA) .getWeekdays();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month);
        cal.set(Calendar.DATE, day);
        int week = cal.get(Calendar.DAY_OF_WEEK);
        int result = 0;
        String value = weekDays[week];
        switch (value)
        {
            case "星期一":
                result = 1;
                break;
            case "星期二":
                result = 2;
                break;
            case "星期三":
                result = 3;
                break;
            case "星期四":
                result = 4;
                break;
            case "星期五":
                result = 5;
                break;
            case "星期六":
                result = 6;
                break;
            case "星期日":
                result = 7;
                break;
        }


        return result;
    }

    /**
     * 根据年份向前推N年的年份集合
     * @param year 年份
     * @param n 向前推N年
     * @return 年份集合字符串，逗号分隔
     */
    public static List getYearsAgoList(int year, int n){
        List list = new ArrayList();
        for(int i = year; i >= year - n; n--){
            list.add(year - n);
            System.out.println(year - n);
        }
        return list;
    }

    public static Date getPreYearAndMonthAndDay(String date) throws Exception
    {
        String year = date.substring(0, 4);
        String month = date.substring(4, 6);
        String day = date.substring(6, 8);

        String year2 = String.valueOf(Integer.parseInt(year) - 1);

        String d = year2 + month + day;

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");

        Date result = format.parse(d);

        return result;
    }

    /**
     * 获取当前日期是星期几<br>
     *
     * @param date
     * @return 当前日期是星期几
     */
    public static String getWeekOfDate(Date date) {
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);

        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0){
            w = 0;
        }

        return weekDays[w];
    }

    /**
     * 获取当前日期中的分钟，并取10的余数
     *
     * @param date
     * @return 当前日期的分钟数
     */
    public static int getCurrentMiNute(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int minute = cal.get(Calendar.MINUTE) - 1;
        return minute;
    }

    /**
     * 根据日期字符串判断当月第几周
     * @param str
     * @return
     * @throws Exception
     */
    public static int getFewWeeks(String str) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(str);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        //第几周
        int week = calendar.get(Calendar.WEEK_OF_MONTH);
        //第几天，从周日开始
        int day = calendar.get(Calendar.DAY_OF_WEEK);
        return week;
    }

    /**
     * 获得本月第一天的日期(字符串格式)
     * @return
     */
    public static String getFirstDayOfMonthString(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-01");
        return sdf.format(new Date());
    }

    /**
     * 获得本月第一天的日期(字符串格式)
     * @return
     */
    public static Date getFirstDayOfMonthDate() throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-01");
        return sdf.parse(sdf.format(new Date()));
    }




    public static Map findWeek(int year, int month, int day){
        DateFormat fmtYearMonthDay = new SimpleDateFormat("yyyy-MM-dd");
        DateFormat fmtMonthDay = new SimpleDateFormat("MMdd");
        SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
        List<Object[]> arrayList = new ArrayList<Object[]>();
        Map map = new HashMap();
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1);

        boolean first = true;
        for(int i=1,j=1; true; ) {
            calendar.set(Calendar.DATE, i);
            int mMonth = calendar.get(Calendar.MONTH);
            int mWeek = calendar.get(Calendar.DAY_OF_WEEK);
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            if(first){
                first = false;
                if(mWeek!=1) {
                    i += (8 - mWeek);

                    continue;
                }
            }
            if(mMonth+1 != month){
                break;
            }
            // End
            Calendar endCalendar = Calendar.getInstance();
            endCalendar.setTime(calendar.getTime());
            endCalendar.add(Calendar.DATE, 6);

            int startDay = Integer.parseInt(sdf.format(calendar.getTime()));
            int endDay = Integer.parseInt(sdf.format(endCalendar.getTime()));
            if(day >= startDay && day <= endDay){
                map.put("dateValue", fmtYearMonthDay.format(calendar.getTime()) + "_" + fmtYearMonthDay.format(endCalendar.getTime()));
                map.put("dateText", "第" + j + "周[" + fmtMonthDay.format(calendar.getTime()) + "-" + fmtMonthDay.format(endCalendar.getTime()) + "]");
            }
            i=i+7;
            j++;
        }
        return map;
    }

    /**
     * 页面初始化显示的年月日和当前第几周的信息
     * @return map（year：年，month：月，dateValue：下拉框中的值，dateText：下拉框中显示的文本）
     */
    public static Map getWeekInfo(){
        SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
        int year = getYear();
        int month = getMonthOfYear();
        int day = getMonthOfYear();
        Map map = findWeek(year,month, Integer.parseInt(sdf.format(new Date())));
        if(map.isEmpty()){
            if(month == 1){
                year = year - 1;
                month = 12;
            }else{
                month = month - 1;
            }
            map = findWeek(year,month, Integer.parseInt(sdf.format(new Date())));
        }
        map.put("year", year);
        map.put("month", month);
        return map;
    }

    public static boolean isValidDate(String date) {
        boolean convertSuccess = true;
        // 指定日期格式为四位年/两位月份/两位日期，注意yyyy/MM/dd区分大小写；
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        try {
            // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
            format.setLenient(false);
            format.parse(date);
        } catch (ParseException e) {
            // e.printStackTrace();
            // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
            convertSuccess = false;
        }
        return convertSuccess;
    }

    /**
     * 获取格式化时间 yyyy-MM-dd HH:mm:ss
     *
     * @return
     */
    public static String getDateFormatter() {
        Date date = new Date();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return df.format(date);
    }


    /**
     * 获取当前时间
     * @param dateformat 日期格式
     * @return
     */
    public static String getNowTime(String dateformat) {
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat(dateformat);
        String hehe = dateFormat.format(now);
        return hehe;
    }

    /**
     * 获取年月日
     * @return
     */
    public static String getYYYYMMdd(int num){
        Calendar cal=Calendar.getInstance();
        cal.add(Calendar.DATE,num);
        Date d=cal.getTime();
        SimpleDateFormat sp=new SimpleDateFormat("yyyy-MM-dd");
        return sp.format(d);
    }

    /**
     * 根据传入的类型返回对应的时间
     * @param type
     * @return
     */
    public static String getDataByType(String type){
        Date date = new Date();
        DateFormat df = new SimpleDateFormat(type);
        return df.format(date);
    }

    /**
     * 获取昨日 年or月or日
     * @param num
     * @param type
     * @return
     */
    public static String getYesterdayBytype(int num,String type){
        Calendar cal=Calendar.getInstance();
        cal.add(Calendar.DATE,num);
        Date d=cal.getTime();
        SimpleDateFormat sp=new SimpleDateFormat(type);
        return sp.format(d);
    }


    /**
     * 根据数字转换星期几
     * @param label
     * @return
     */
    public static String getWeek(String label){
        if(label.equals("1")){
            return "星期日";
        }else if(label.equals("2")){
            return "星期一";
        }else if(label.equals("3")){
            return "星期二";
        }else if(label.equals("4")){
            return "星期三";
        }else if(label.equals("5")){
            return "星期四";
        }else if(label.equals("6")){
            return "星期五";
        }else if(label.equals("7")){
            return "星期六";
        }
        return "星期日";
    }

    public static String dayForWeek(String pTime) throws Throwable {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date tmpDate = format.parse(pTime);
        Calendar cal = Calendar.getInstance();
        String[] weekDays = { "7", "1", "2", "3", "4", "5", "6" };
        try {
            cal.setTime(tmpDate);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0){
            w = 0;
        }
        return weekDays[w];

    }


    public static Integer getWeek(Date date){
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        Integer[] weeks = {7,1,2,3,4,5,6};
        int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if(week_index<0){
            week_index = 0;
        }
        return weeks[week_index];
    }

    /**
     * 计算今日昨日的环比增长率
     * @param today
     * @param yesterday
     * @return
     */
    public static String grow(Integer today,Integer yesterday){
        if (today == 0 ){
            return "-100%";
        }
        if(yesterday==0){
            return "100%";
        }
        NumberFormat numberFormat = NumberFormat.getInstance();
        // 设置精确到小数点后2位
        numberFormat.setMaximumFractionDigits(2);
        String result = numberFormat.format((float) today / (float) yesterday * 100-100);
        System.out.println(result);
        result = Math.round(Double.parseDouble(result)) + "%";
        return result;
    }


    /**
     * 时间戳转换成日期格式字符串
     * @param seconds
     * @param format 精确到秒的字符串
     * @return
     */
    public static String timeMillisToData(String seconds,String format) {
        if(seconds == null || seconds.isEmpty()){
            return "";
        }
        if(format == null || format.isEmpty()){
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(seconds+"000")));
    }


    /**
     * 获取多少秒前、后的时间
     * @param second
     * @return
     */
    public static String getDateBySecond(String dd, int second){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = new GregorianCalendar();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = df.parse(dd);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        c.setTime(date);
        c.add(Calendar.SECOND,second);
        date=c.getTime();
        return sdf.format(date);
    }

}
